import { Component, OnInit } from '@angular/core';
import { FetchService } from '../../../core/net/fetch.service';
import { UtilService } from '../../../core/util/util.service';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService, UploadXHRArgs } from 'ng-zorro-antd';
import * as moment from 'moment';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';

@Component({
    selector: 'app-sub-year-plan-add',
    templateUrl: './sub-year-plan-add.component.html',
    styleUrls: ['./sub-year-plan-add.component.scss']
})
export class SubYearPlanAddComponent implements OnInit {
    year = moment().add(1, 'y').year();    // 默认查后一年
    pageType: string;   //  add edit detail
    planName = '';
    sectionId = JSON.parse(localStorage.userInfo).sectionId;

    leftList = [];
    serverUrl = (window as any).environment.reportUrl;
    iframeSrc: SafeResourceUrl;
    downloadId;
    uploadUrl = `${(window as any).environment.apiBaseUrl}comm/exceldb/importExcel`;

    constructor(
        private fetchService: FetchService,
        private util: UtilService,
        private routerInfo: ActivatedRoute,
        private router: Router,
        private sanitizer: DomSanitizer,
        private message: NzMessageService,
        private http: HttpClient,
        private modal: NzModalService
    ) {
        this.year = this.routerInfo.snapshot.queryParams['year'] || moment().add(1, 'y').year();
        this.pageType = this.routerInfo.snapshot.queryParams['type'];
        this.planName = this.routerInfo.snapshot.queryParams['name'] || '年计划';
        this.sectionId = this.routerInfo.snapshot.queryParams['sectionId'] || JSON.parse(localStorage.userInfo).sectionId;
    }

    ngOnInit(): void {
        if (this.pageType === 'add') {
            switch (this.sectionId) {
                case '168':
                    this.planName = `宁西公司第一管理所${this.year}年夏秋灌冬灌用水计划`;
                    this.downloadId = '3efb9c850c654d11bda0efd232023a36';
                    break;
                case  '169':
                    this.planName = `宁西公司第二管理所${this.year}年夏秋灌冬灌用水计划`;
                    this.downloadId = 'a155c38938744a4ba1180c2d12ef1afc';
                    break;
                default:
                    this.planName = `${this.year}年夏秋灌冬灌用水计划`;
                    this.downloadId = '';
                    break;
            }
        }
        this.queryLeftList();
    }

    queryLeftList(): void {
        this.fetchService.post('sys/sysApiInfo/queryApiData', {
            apicode: 35,
            sectionId: this.sectionId
        }).subscribe(res => {
            if (res && Array.isArray(res)) {
                this.leftList = res;
                this.selectedAreaChanged(res[0].sheet);
            }
        });
    }

    selectedAreaChanged(sheet): void {
        const link = `${this.serverUrl}preview?_u=wrs:跃进渠年计划报表.ureport.xml&y=${this.year}&section_id=${this.sectionId}&sheet=${sheet}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
    }

    download(): void {
        this.fetchService.export(`comm/file/down/${this.downloadId}`, {
            responseType: 'blob'
        }).subscribe(data => {
            const fileBlob = new Blob([data], {type: 'charset=utf-8'});
            const link = document.createElement('a');
            link.id = 'downloadId';
            document.body.appendChild(link);
            link.style.display = 'none';
            link.download = this.planName;
            link.href = URL.createObjectURL(fileBlob);
            link.click();
            const tempA = document.getElementById('downloadId');
            if (tempA) {
                tempA.parentNode.removeChild(tempA);
            }
        });
    }

    customReq = (item: UploadXHRArgs) => {
        const formData = new FormData();
        formData.append('excelfile', item.file as any);
        formData.append('excelMapper', 'ExcelMapper-wrsExcelLwPlan');
        formData.append('errorWriteback', 'YES');
        formData.append('queryParams', JSON.stringify({
            type: 1,
            year: this.year
        }));
        const req = new HttpRequest('POST', item.action!, formData, {
            reportProgress: true,
            withCredentials: false
        });
        return this.http.request(req).subscribe(
            (event: HttpEvent<{}>) => {
                if (event.type === HttpEventType.UploadProgress) {
                    if (event.total! > 0) {
                        // tslint:disable-next-line:no-any
                        (event as any).percent = (event.loaded / event.total!) * 100;
                    }
                    item.onProgress!(event, item.file!);
                } else if (event instanceof HttpResponse) {
                    item.onSuccess!(event.body, item.file!, event);
                    if (event.body['error']) {
                        this.message.error(`上传失败，原因：'${event.body['error'].msg}'；`);
                    } else {
                        this.message.success('数据上传成功');
                    }
                    this.selectedAreaChanged(this.leftList[0].sheet);
                }
            },
            err => {
                item.onError!(err, item.file!);
                this.message.error('上传失败，请重新上传');
            }
        );
    }

    goBack(): void {
        this.router.navigate(['/dispatch-plan/sub-year-plan']);
    }
}
